import axios from 'axios';

type Config = {
  url: string;
  method: 'get' | 'post';
  data?: any;
  params?: any;
};

axios.defaults.baseURL = SERVICE_URL;

const request = (option: Config, headers?: { [property: string]: string }) => {
  return new Promise((resolve, reject) => {
    const timeC = parseInt(new Date().getTime() / 1000 + '');
    const token = sessionStorage.getItem('token');
    const version = sessionStorage.getItem('version');
    axios({
      ...option,
      headers: {
        ...(headers ?? {}),
        version: version ?? '',
        time: timeC + '',
        Authorization: token !== '' ? `Bearer ${token}` : '',
      },
    })
      .then((res) => {
        const { data, status } = res;
        if (status === 200) {
          const { code } = data;
          if (code === 0) {
            resolve(data);
          } else {
            reject(data);
          }
        } else {
          reject(res);
        }
      })
      .catch((err) => {
        reject(err);
      });
  });
};

export default request;
